package cn.softeem.tushu.utils;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class BeanUtil {
    public static <T> T toBean(Map<String, String[]> map, Class<T> clazz) {
        try {
            T obj = clazz.newInstance();
            PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
            for (PropertyDescriptor pd : pds) {
                String pName = pd.getName();
                if (map.containsKey(pName)) {
                    if (pd.getPropertyType() == Integer.class) {
                        pd.getWriteMethod().invoke(obj, Integer.valueOf(map.get(pName)[0]));
                    } else if (pd.getPropertyType() == Long.class) {
                        pd.getWriteMethod().invoke(obj, Long.valueOf(map.get(pName)[0]));
                    } else if (pd.getPropertyType() == String.class) {
                        pd.getWriteMethod().invoke(obj, String.valueOf(map.get(pName)[0]));
                    } else if (pd.getPropertyType() == Date.class) {
                        pd.getWriteMethod().invoke(obj, new SimpleDateFormat("yyyy-mm-dd").parse(map.get(pName)[0]));
                    } else if (pd.getPropertyType() == String[].class) {
                        pd.getWriteMethod().invoke(obj, (Object) map.get(pName));
                    }else if (pd.getPropertyType() == Double.class) {
                        pd.getWriteMethod().invoke(obj, Double.valueOf(map.get(pName)[0]));
                    }
                }
            }
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static <T> T toBeans(Map map, Class<T> clazz) {
        try {
            /*
             * 1. 通过参数clazz创建实例
             * 2. 使用BeanUtils.populate把map的数据封闭到bean中
             */
            T bean = clazz.newInstance();
            ConvertUtils.register(new DateConverter(), java.util.Date.class);
            BeanUtils.populate(bean, map);
            return bean;
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }
}
